<!-- 跟进提报 -->
<template>
  <div class="has-foot-pb">
    <div class="d-header">
      <div class="d-header-top">
        <div class="round"><img src="@/assets/images/store.png" /></div>
        <span class="color-black"> {{ detail.marketName }}</span>
      </div>
      <div class="d-header-address">
        <img src="@/assets/images/position.png" />
        <div>{{ detail.address }}</div>
      </div>
      <div class="d-header-bottom">
        <div>
          市场类型：<span class="color-black">{{ getDictName('TOBE_MARKET_TYPE', detail.marketType) }}</span>
        </div>
        <div>
          市场属性：<span class="color-black">{{ getDictName('MARKET_NATURE', detail.marketNatrue) }}</span>
        </div>
        <!-- <div>
          数据来源：<span class="color-black">{{ getDictName('CTM_MARKET_DATA_FROM', detail.dataSource) }}</span>
        </div>
        <div>
          数据来源描述：<span class="color-black">{{ detail.dataSourceMsg }}</span>
        </div>
        <div>
          考核计划：<span class="color-black">{{ getDictName('CTM_APPRAISAL_PLAN', detail.appraisalPlan) }}</span>
        </div> -->
      </div>
      <div class="tags">
        <span class="tag-rd">跟进日期：{{ detail.createTime }}</span>
      </div>
    </div>

    <!-- <Cell title="是否有进展" :custom="true" :right="false">
      <qmp-switch v-model="formData.isProgress" :active-value="1" :inactive-value="0">
        <template #background>
          <span class="qmp-switch__background"> {{ formData.isProgress === 1 ? '是' : '否' }}</span>
        </template>
      </qmp-switch>
    </Cell> -->
    <div v-if="formData.isProgress === 1">
      <FieldSelect
        v-model="formData.progressStage"
        title="进展程度"
        :url="`/data-dict/app/v2/dictionary/CTM_MARKET_BUID_FOLLOW_UP_PROGRESS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
        required
      />

      <Cell
        title="是否有意向经销商"
        :custom="true"
        :right="false"
        required
        subTitle="老商整改或开分店，选择是"
        v-if="detail.marketType !== 'B' && detail.marketNatrue !== 'L'"
      >
        <!-- detail.marketNatrue !== 'L' 增开分店 -->
        <qmp-switch v-model="formData.isIntendedDealer" :active-value="1" :inactive-value="0">
          <template #background>
            <span class="qmp-switch__background"> {{ formData.isIntendedDealer === 1 ? '是' : '否' }}</span>
          </template>
        </qmp-switch>
      </Cell>
      <div
        v-if="detail.marketType !== 'B' && detail.marketNatrue !== 'L' && formData.isIntendedDealer"
        class="is-dealer"
      >
        <Cell
          title="商家姓名"
          v-model="formData.dealerName"
          divider
          :right="false"
          :isInput="true"
          required
          input-align="right"
          placeholder="输入商家姓名"
        />
        <Cell
          title="商家年龄"
          v-model="formData.dealerAge"
          divider
          :right="false"
          :isInput="true"
          required
          input-align="right"
          placeholder="输入商家年龄"
        />
        <FieldSelect
          v-model="formData.intentionLevel"
          title="商家意向等级"
          class="other-cell"
          subTitle="A类：确定与全友合作意向，有合作实力，有合适口岸，可快速签约;
B类：明确与全友合作意向，但可能资金不足或口岸不达标；
C类：有明确投资意向，对全友或其他竞品品牌；"
          required
          :url="`/data-dict/app/v2/dictionary/CTM_INTENTION_LEVEL`"
          label-name="dictName"
          value-name="dictCode"
          method="get"
          :params="dictParams"
          clear
        />
        <FieldSelect
          v-model="formData.isPayEarmestMoney"
          title="是否缴纳保证金/意向金"
          required
          label-name="label"
          value-name="value"
          :optionData="[
            { label: '是', value: 1 },
            { label: '否', value: 0 }
          ]"
          clear
        />
        <FieldDateTime
          v-model="formData.payEarmestMoneyTime"
          title="保证金缴纳时间"
          placeholder="选择保证金缴纳日期"
          type="date"
          :default-date="formData.payEarmestMoneyTime"
          clear
        />
        <Cell title="现经营品牌/行业资历" is-column custom divider :right="false" required>
          <qmp-field
            v-model="formData.industryQualification"
            type="textarea"
            placeholder="输入现经营品牌/行业资历"
            class="ctm-text-area"
          />
        </Cell>
        <Cell title="是否到店/公司参观" :custom="true" :right="false" required>
          <qmp-switch v-model="formData.isArriveShore" :active-value="1" :inactive-value="0">
            <template #background>
              <span class="qmp-switch__background"> {{ formData.isArriveShore === 1 ? '是' : '否' }}</span>
            </template>
          </qmp-switch>
        </Cell>
        <Cell
          title="预算投入金额"
          v-model="formData.budgetedAmount"
          divider
          :right="false"
          :isInput="true"
          required
          input-align="right"
          placeholder="输入金额"
          unit="万"
        />
        <FieldSelect
          v-model="formData.isSuitableSite"
          title="是否有合适场地"
          label-name="label"
          value-name="value"
          method="get"
          required
          :optionData="[
            { label: '是', value: 1 },
            { label: '否', value: 0 }
          ]"
          clear
        />
        <Cell
          title="预估面积"
          v-model="formData.estimatedArea"
          divider
          :right="false"
          :isInput="true"
          :required="formData.isSuitableSite === 1"
          input-align="right"
          placeholder="输入预估面积"
        />
        <Cell title="场地详细地址" is-column custom divider :right="false" :required="formData.isSuitableSite === 1">
          <qmp-field v-model="formData.address" type="textarea" placeholder="输入场地详细地址" class="ctm-text-area" />
        </Cell>
        <Cell
          title="请补充完末级地址信息，如区县、街道、xx路、xx号"
          :custom="true"
          isColumn
          :right="false"
          cellClassName="redTips"
        />
      </div>

      <FieldSelect
        v-if="detail.marketType !== 'B' && detail.marketNatrue === 'L'"
        v-model="formData.isSuitableSite"
        title="是否有合适场地"
        label-name="label"
        value-name="value"
        method="get"
        required
        :optionData="[
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ]"
        clear
      />
      <div
        v-if="detail.marketType !== 'B' && detail.marketNatrue === 'L' && formData.isSuitableSite === 1"
        class="is-dealer"
      >
        <FieldSelect
          v-model="formData.isPayEarmestMoney"
          title="是否缴纳保证金/意向金"
          required
          label-name="label"
          value-name="value"
          :optionData="[
            { label: '是', value: 1 },
            { label: '否', value: 0 }
          ]"
          clear
        />
        <FieldDateTime
          v-model="formData.payEarmestMoneyTime"
          title="保证金缴纳时间"
          placeholder="选择保证金缴纳日期"
          type="date"
          :default-date="formData.payEarmestMoneyTime"
          clear
        />

        <Cell
          title="预算投入金额"
          v-model="formData.budgetedAmount"
          divider
          :right="false"
          :isInput="true"
          required
          input-align="right"
          placeholder="输入金额"
          unit="万"
        />
        <Cell
          title="预估面积"
          v-model="formData.estimatedArea"
          divider
          :right="false"
          :isInput="true"
          :required="formData.isSuitableSite === 1"
          input-align="right"
          placeholder="输入预估面积"
        />
        <Cell title="场地详细地址" is-column custom divider :right="false" :required="formData.isSuitableSite === 1">
          <qmp-field v-model="formData.address" type="textarea" placeholder="输入场地详细地址" class="ctm-text-area" />
        </Cell>
        <Cell
          title="请补充完末级地址信息，如区县、街道、xx路、xx号"
          :custom="true"
          isColumn
          :right="false"
          cellClassName="redTips"
        />
      </div>

      <FieldDateTime
        v-model="formData.estimatedSurveyTime"
        title="预计测绘时间"
        placeholder="选择预计测绘时间"
        type="date"
        clear
      />

      <FieldDateTime
        v-model="formData.estimatedDrawingTime"
        title="预计报图时间"
        placeholder="选择预计报图时间"
        type="date"
        clear
      />
    </div>
    <Cell title="跟进说明" is-column custom divider :right="false" required>
      <qmp-field v-model="formData.remark" type="textarea" placeholder="填写跟进说明" class="ctm-text-area" />
    </Cell>

    <Cell
      v-if="!formData.isProgress"
      title="无进展时，请详细描述开展计划、市场情况、陌拜结果、人口、楼盘等情况"
      :custom="true"
      isColumn
      :right="false"
      cellClassName="redTips"
    />

    <div class="header">最后一次审核结果</div>
    <Cell
      class="more-class"
      title="审核结果"
      :modelValue="detail.aduitStatus"
      dict-type-code="REVIEW_RESULT"
      default-value="--"
      readonly
    />

    <Cell class="more-class" title="审核意见" :modelValue="detail.aduitFialRemark" default-value="" readonly custom />

    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSubmit">提交</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick } from 'vue'
  import Cell from '@/components/Cell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import FieldDateTime from '@/components/FieldDateTime/index.vue'
  // import Card from '@/components/Card/index.vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { marketDataDetail, submit } from '@/apis/storeUpgrade/index'
  import { initFormData, isChange } from '@/utils'
  import { getDictByPatchType } from '@/apis/dataDict'
  import GetKeyboardMixin from '@/utils/useKeyboard'

  interface anyObjectModle {
    id: any
    dictParams: object
    formData: any
    originalData: string
    detail: any
    dictData: any
    submiting: boolean
    isEditBack: boolean
    [key: string]: any
  }
  const none: any[] = [undefined, null, '']
  export default {
    name: 'StoreUpgradeTaskEdit',
    components: { Cell, FieldSelect, FieldDateTime },
    setup() {
      const $route = useRoute()
      const $router = useRouter()
      const { proxy }: any = getCurrentInstance()

      const state = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        formData: {
          id: '',
          isProgress: 0,
          progressStage: '',
          isIntendedDealer: 0,
          dealerName: '',
          dealerAge: '',
          intentionLevel: '',
          isPayEarmestMoney: 0,
          payEarmestMoneyTime: '',
          industryQualification: '',
          isArriveShore: 0,
          budgetedAmount: '',
          isSuitableSite: '',
          estimatedArea: '',
          address: '',
          estimatedSurveyTime: '',
          estimatedDrawingTime: '',
          remark: ''
        },
        originalData: '', // 原始数据 用于对比值是否发生变化
        detail: {},
        dictData: {},
        submiting: false,
        isEditBack: false // 是否是编辑成功后返回
      })
      state.keyboard = {
        show: false
      }
      state.keyboard = GetKeyboardMixin()

      // 阻止返回
      onBeforeRouteLeave((to, from, next) => {
        if (state.isEditBack || isChange(state.formData, state.originalData)) next()
        else {
          proxy.$dialog
            .confirm({
              title: '当前编辑数据未保存，是否确认退出？',
              theme: 'round-button',
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              showCancelButton: true,
              closeOnPopstate: false
            })
            .then(() => {
              next()
            })
            .catch(() => {
              next(false)
            })
        }
      })

      const onSubmit = () => {
        if (state.submiting) return
        const data = { ...state.formData }

        if (data.isProgress === 1) {
          if (none.includes(data.progressStage)) {
            proxy.$toast('请选择进展程度')
            return
          }

          if (state.detail.marketType !== 'B' && state.detail.marketNatrue !== 'L') {
            if (none.includes(data.isIntendedDealer)) {
              proxy.$toast('请选择是否有意向经销商')
              return
            }

            //   dealerAge 商家年龄
            if (data.isIntendedDealer === 1) {
              if (none.includes(data.dealerName)) {
                proxy.$toast('请输入商家姓名')
                return
              }

              if (none.includes(data.dealerAge)) {
                proxy.$toast('请输入商家年龄')
                return
              }

              // let regAge = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/
              // if (data.dealerAge && !regAge.test(data.dealerAge)) {
              //   proxy.$toast('年龄输入不合法')
              //   return
              // }

              if (none.includes(data.intentionLevel)) {
                proxy.$toast('请选择商家意向等级')
                return
              }

              if (none.includes(data.isPayEarmestMoney)) {
                proxy.$toast('请选择是否缴纳保证金/意向金')
                return
              }

              if (none.includes(data.industryQualification)) {
                proxy.$toast('请输入现经营品牌/行业资历')
                return
              }

              if (none.includes(data.budgetedAmount)) {
                proxy.$toast('请输入预算投入金额')
                return
              }
              const regPrice = /^[0-9]*[1-9][0-9]*$/
              if (data.budgetedAmount && !regPrice.test(data.budgetedAmount)) {
                proxy.$toast('预算投入金额输入不合法')
                return
              }

              if (none.includes(data.isSuitableSite)) {
                proxy.$toast('请选择是否有合适场地')
                return
              }
              if (data.isSuitableSite === 1) {
                if (none.includes(data.estimatedArea)) {
                  proxy.$toast('请输入预估面积')
                  return
                }
                const regArea = /^[1-9][0-9]*([\.][0-9]{1,2})?$/
                if (data.estimatedArea && !regArea.test(data.estimatedArea)) {
                  proxy.$toast('预估面积输入不合法')
                  return
                }

                if (none.includes(data.address)) {
                  proxy.$toast('请输入场地详细地址')
                  return
                }
              }
            }
          } else if (state.detail.marketType !== 'B' && state.detail.marketNatrue === 'L') {
            if (none.includes(data.isSuitableSite)) {
              proxy.$toast('请选择是否有合适场地')
              return
            }

            if (data.isSuitableSite === 1) {
              if (none.includes(data.isPayEarmestMoney)) {
                proxy.$toast('请选择是否缴纳保证金/意向金')
                return
              }

              if (none.includes(data.budgetedAmount)) {
                proxy.$toast('请输入预算投入金额')
                return
              }
              const regPrice = /^[0-9]*[1-9][0-9]*$/
              if (data.budgetedAmount && !regPrice.test(data.budgetedAmount)) {
                proxy.$toast('预算投入金额输入不合法')
                return
              }

              if (none.includes(data.estimatedArea)) {
                proxy.$toast('请输入预估面积')
                return
              }
              const regArea = /^[1-9][0-9]*([\.][0-9]{1,2})?$/
              if (data.estimatedArea && !regArea.test(data.estimatedArea)) {
                proxy.$toast('预估面积输入不合法')
                return
              }

              if (none.includes(data.address)) {
                proxy.$toast('请输入场地详细地址')
                return
              }
            }
          }
        }
        if (none.includes(data.remark)) {
          proxy.$toast('请输入跟进说明')
          return
        }
        state.submiting = true
        submit(data)
          .then((res: any) => {
            if (res.success === 1) {
              proxy.$toast('提报成功')
              proxy.$SimpleEvents.emit('refreshCustomerChangeItem')

              nextTick(() => {
                state.isEditBack = true
                $router.goBack()
              })
              state.submiting = false
            }
          })
          .catch((e: any) => {
            if (e) proxy.$toast(e)
            state.submiting = false
          })
      }

      const getDictName = (dictType: string, code: any) => {
        if (!dictType || [undefined, null, ''].includes(code)) return ''
        let name = code
        const dictList = state.dictData[dictType] || []
        if (dictList.length > 0) {
          const obj = dictList.find((v: any) => v.dictCode === `${code}`)
          name = obj?.dictName || code
        }
        return name
      }

      const getDetail = () => {
        const id = `${state.id}`

        marketDataDetail(id).then((res: any) => {
          state.detail = res.data

          initFormData(res.data, state.formData)

          const { isProgress, isIntendedDealer, isPayEarmestMoney, isArriveShore } = res.data

          if (none.includes(isProgress)) state.formData.isProgress = 0
          if (none.includes(isIntendedDealer)) state.formData.isIntendedDealer = 0
          if (none.includes(isPayEarmestMoney)) state.formData.isPayEarmestMoney = 0
          if (none.includes(isArriveShore)) state.formData.isArriveShore = 0

          state.originalData = JSON.stringify(state.formData)
        })
      }
      getDetail()
      // 获取数据字典
      const getDictData = async () => {
        const dictTypeCodes = [
          // 'CTM_MARKET_BUID_FOLLOW_UP_PROGRESS',
          'TOBE_MARKET_TYPE',
          // 'CTM_MARKET_BUID_WEEK_MAINTENANCE_PROGRESS',
          // 'CTM_INTENTION_LEVEL'
          'MARKET_NATURE'
          // 'CTM_MARKET_DATA_FROM',
          // 'CTM_APPRAISAL_PLAN'
        ]
        state.dictData = await getDictByPatchType({ dictTypeCodes })
      }

      getDictData()
      return {
        ...toRefs(state),
        onSubmit,
        getDictName
      }
    }
  }
</script>

<style lang="less" scoped>
  .d-header {
    padding: 14px;
    background-color: var(--bg-global-weaker);
    margin: 8px 0;
    .d-header-top {
      display: flex;
      align-items: center;
      height: 24px;
      font: var(--font-main-title-strengthen);
      .round {
        width: 24px;
        height: 24px;
        background: var(--texticon-color-warning-normal);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 8px;

        img {
          width: 16px;
          height: 16px;
        }
      }
    }

    .d-header-address {
      display: flex;
      align-items: center;
      margin-top: 4px;
      height: 24px;
      font: var(--font-main-body);
      color: var(--texticon-default-stronger);

      img {
        width: 20px;
        height: 20px;
        margin-right: 8px;
        padding: 2px;
      }
    }

    .d-header-bottom {
      font: var(--font-main-body);
      color: var(--texticon-default-stronger);

      div {
        margin: 8px 0;
        width: calc(100% - 100px);
      }
    }

    .tags {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      .tag-rd {
        display: inline-flex;
        padding: 4px 8px;
        margin-right: 4px;
        border-radius: 2px;
        background: var(--bg-focusing-brand);
        font: var(--font-main-body);
        color: var(--texticon-color-brand-normal);
      }
    }
  }

  .header {
    margin-top: 8px;
    height: 20px;
    font: var(--font-main-body);
    color: var(--texticon-default-stronger);
    background: var(--bg-global-weaker);
    padding: 8px 14px;
    position: relative;

    &::after {
      position: absolute;
      content: '';
      width: calc(100% - 28px);
      height: 1px;
      bottom: 0;
      left: 14px;
      background: var(--divisionline-weak);
    }
  }

  .is-dealer {
    /deep/ .c-cell {
      background: var(--bg-global-normal);
    }
  }
  .more-class {
    /deep/ .label {
      color: var(--texticon-default-strong) !important;
    }
  }

  .redTips {
    /deep/ .black {
      color: var(--texticon-color-error-normal) !important;
    }
  }
  .other-cell {
    /deep/ .sub-label {
      width: 240px;
      white-space: pre-wrap;
    }
  }
</style>
